<?php
declare (strict_types = 1);

namespace app\service\logic\common\order;

use app\constant\LogicConstant;
use app\exception\LogicException;
use app\facade\ALiPayFacade;
use app\facade\StringFacade;
use app\facade\WechatpayFacade;
use app\model\communal\ImMessageModel;
use app\model\communal\OrderConsultModel;
use app\model\communal\OrderConsultRefundLogModel;
use app\model\communal\OrderConsultRefundModel;
use app\model\communal\OrderMultiModel;
use app\model\communal\ScaleMultiExpertModel;
use app\model\communal\UserExpertItemModel;
use app\service\logic\BaseService;
use app\service\logic\common\chat\ChatService;
use app\service\logic\common\maintain\InfoService;
use app\service\logic\common\user\ExpertAmountService;
use app\service\logic\common\user\ExpertStatisticsService;
use app\service\logic\common\user\StatisticsService;
use Carbon\Carbon;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\facade\Log;
use think\Model;

final class OrderConsultService extends BaseService
{
    protected string $modelClassName = 'OrderConsultModel';

    /**
     * 获取复杂列表
     *
     * @param $params
     * @param $search_fields
     * @param $search
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getComplexList($params, $search_fields, $search)
    {
        $with = ['belongUser', 'byCreator', 'belongExpert'];
        $fun = function ($item) {
            list($item['status_map'], $item['status_sub']) = $this->getStatusMap($item['status'], $item);
            $item['purchase_time_map'] = $item['purchase_time'] / 60; // s换算min
            $item['consult_method_map'] = 1 == $item['consult_method'] ? '语音咨询' : '视频咨询';
            $item['payment_type_map'] = $this->getPaymentTypeMap($item['payment_type']);
            unset($item['belongUser'], $item['byCreator'], $item['belongExpert']);
            return $item;
        };
        return parent::getList($params, $search_fields, $search, $with, $fun);
    }

    /**
     * 生成量表解读订单
     *
     * @param $params
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function createFromInterpret($params)
    {
        $multiId = $params['multi_id']; // 心理测试订单id
        $order = OrderMultiModel::findOrFail($multiId);
        $scaleMultiId = $order['scale_multi_id']; // 多元智能题型id
        $expertId = $params['expert_id'];
        // 获取该题型解读师金额
        $multiExpert = ScaleMultiExpertModel::where('scale_multi_id', $scaleMultiId)->where('expert_id', $expertId)->findOrFail();
        $amount = $multiExpert['amount']; // 单价金额, 量表解读单价既 // 总金额

        // 获取可用元心币
        $availableCoin = invoke(StatisticsService::class)->getCoinAvailableCountByUserId($params['user_id']);
        $deductCoin = 1 == $params['is_coin'] ? $availableCoin : '0'; // 抵扣用元心币数量
        list($paymentAmount, $deductAmount, $deductCoin) = StringFacade::orderPayment($amount, $deductCoin);

        $orderInsert = [
            'user_id' => $params['user_id'],
            'expert_id' => $expertId,
            'morph_id' => $scaleMultiId,
            'status' => $paymentAmount > 0 ? 1 : 2,
            'name' => $order['scale_multi_name'],
            'amount' => $amount,
            'purchase_time' => 30 * 60, // 默认30min
            'total_amount' => $amount,
            'payment_amount' => $paymentAmount,
            'deduct_amount' => $deductAmount,
            'deduct_coin' => $deductCoin,
            'payment_type' => $params['payment_type'],
            'type' => 1,
        ];

        Db::connect('communal')->transaction(function () use ($orderInsert, &$model) {
            $model = OrderConsultModel::create($orderInsert);
            $number = StringFacade::createStringById($model['id'], 'OC', 16);
            $model->save(['number' => $number]);

            // 支付成功前需要锁定元心币
            if ($orderInsert['deduct_coin'] > 0) {
                // 需要锁定
                invoke(StatisticsService::class)->freezeCoin($model['user_id'], $model['deduct_coin']);
            }
        });
        return $model;
    }

    /**
     * 生成心理咨询订单
     *
     * @param $params
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function createFromItem($params)
    {
        $itemId = $params['item_id']; // 服务项目id
        $item = UserExpertItemModel::where('id', $itemId)->where('expert_id', $params['expert_id'])->findOrFail();
        $expertId = $params['expert_id'];
        // 获取该项目单价金额
        $amount = $item['amount']; // 单价金额
        $totalAmount = $params['purchase_min'] / 30 * $amount; // 总金额
        // 获取可用元心币
        $availableCoin = invoke(StatisticsService::class)->getCoinAvailableCountByUserId($params['user_id']);
        $deductCoin = 1 == $params['is_coin'] ? $availableCoin : '0'; // 抵扣用元心币数量
        list($paymentAmount, $deductAmount, $deductCoin) = StringFacade::orderPayment($totalAmount, $deductCoin);

        $orderInsert = [
            'user_id' => $params['user_id'],
            'expert_id' => $expertId,
            'morph_id' => $item['id'],
            'status' => $paymentAmount > 0 ? 1 : 2,
            'name' => $item['name'],
            'amount' => $amount,
            'purchase_time' => $params['purchase_min'] * 60,
            'total_amount' => $totalAmount,
            'payment_amount' => $paymentAmount,
            'deduct_amount' => $deductAmount,
            'deduct_coin' => $deductCoin,
            'consult_method' => $params['consult_method'],
            'payment_type' => $params['payment_type'],
            'type' => 2,
        ];

        Db::connect('communal')->transaction(function () use ($orderInsert, &$model) {
            $model = OrderConsultModel::create($orderInsert);
            $number = StringFacade::createStringById($model['id'], 'OC', 16);
            $model->save(['number' => $number]);

            // 支付成功前需要锁定元心币
            if ($orderInsert['deduct_coin'] > 0) {
                // 需要锁定
                invoke(StatisticsService::class)->freezeCoin($model['user_id'], $model['deduct_coin']);
            }
        });

        return $model;
    }

    /**
     * 订单状态处理
     *
     * @param $type
     * @param $data
     * @return string[]
     */
    public function getStatusMap($type, $data)
    {
        $map = '';
        $statusSub = 0;
        if (1 == $data['refund_status'] || 4 == $data['refund_status']) {
            // 未审核 || 已取消 || 审核驳回
            switch ($type) {
                // 1 待支付 2 待预约时间 3 待开始 4 进行中 5 待填写报告 6 已完成 7 已取消 8 退款审核通过
                case 1:
                    $map = '待支付';
                    $statusSub = 1;
                    break;
                case 2:
                    $map = '待预约时间';
                    $statusSub = 2;
                    break;
                case 3:
                    /*
                     * 时间需求不要了,就是这么随意-!-🤢🤢🤢
                     */
                    // 到达预约时间为进行中
                    // $currentAt = Carbon::now()->timestamp;
                    // $consultAt = Carbon::createFromFormat('Y-m-d H:i:s', $data['consult_at'])->timestamp;
                    // if ($consultAt <= $currentAt) {
                    //     $map = '进行中';
                    //     $statusSub = 4;
                    // } else {
                    //     $map = '待开始';
                    //     $statusSub = 3;
                    // }

                    $map = '待开始';
                    $statusSub = 3;
                    break;
                case 4:
                    $map = '进行中';
                    $statusSub = 4;
                    break;
                case 5:
                    $map = '待填写报告';
                    $statusSub = 5;
                    break;
                case 6:
                    $map = '已完成';
                    $statusSub = 6;
                    break;
                case 7:
                    $map = '已取消';
                    $statusSub = 7;
                    break;
            }
        } else {
            switch ($data['refund_status']) {
                case 2:
                    $map = '退款审核中';
                    $statusSub = 102;
                    break;
                case 3:
                    $map = '退款审核通过';
                    $statusSub = 103;
                    break;
            }
        }

        return [$map, $statusSub];
    }

    /**
     * 排序参数
     *
     * @param $params
     * @param string $column
     * @param string $type
     * @return array|string[]
     */
    public function orderByParams($params, string $column = 'id', string $type = 'desc')
    {
        if (
            isset($params['order_option']) &&
            in_array($params['order_option'], [OrderConsultModel::ORDER_OPTION_ONE, OrderConsultModel::ORDER_OPTION_TWO])
        ) {
            $orderField = OrderConsultModel::$orderRuleMap[$params['order_option']]['orderBy'];
            $orderDir = OrderConsultModel::$orderRuleMap[$params['order_option']]['orderDir'];
            $order = [$orderField => $orderDir, 'id' => 'desc'];
            unset($params['order_option']);
        } else {
            $orderField = isset($params['orderBy']) && !empty($params['orderBy']) ? $params['orderBy'] : $column;
            $orderDir = isset($params['orderDir']) && !empty($params['orderDir']) ? $params['orderDir'] : $type;
            $order = [$orderField => $orderDir];
        }

        return $order;
    }

    /**
     * 预约时间/变更时间
     *
     * @param $params
     * @return array|mixed|Model
     * @throws DataNotFoundException
     * @throws LogicException
     * @throws ModelNotFoundException
     */
    public function reserve($params)
    {
        $model = $this->getSimpleDetail($params);
        if (!in_array($model['status'], [2, 3])) {
            throw new LogicException('不可预约/变更时间');
        }

        $update = [
            'consult_at' => $params['consult_at'],
            'status' => 3,
        ];
        $model->save($update);
        return $model;
    }

    /**
     * 订单发起通话
     *
     * @param $params
     * @return array|mixed|Model
     * @throws DataNotFoundException
     * @throws LogicException
     * @throws ModelNotFoundException
     */
    public function call($params)
    {
        $model = $this->getSimpleDetail($params);
        if ($model['status'] != 3) {
            throw new LogicException('不可发起通话');
        }
        unset($params['id']);

        Db::connect('communal')->transaction(function () use ($params, &$model) {
            // 发送到用户聊天消息
            $params['receiver_id'] = $model['user_id'];
            $params['receiver_type'] = ImMessageModel::MORPH_TYPE_TWO;
            $params['type'] = ImMessageModel::TYPE_THREE;
            $params['content'] = json_encode($model, JSON_UNESCAPED_UNICODE);
            invoke(ChatService::class)->create($params);

            // 接听通话后才变为进行中
            // $update = ['status' => 4];
            // $model->save($update);
        });

        return $model;
    }

    /**
     * 订单进行中 搞里头
     *
     * @param $params
     * @return array|mixed|Model
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function going($params)
    {
        $model = $this->getSimpleDetail($params);

        // if (3 != $model['status']) {
        //     throw new LogicException('不可设置进行中');
        // }

        $model->save(['status' => 4]);
        return $model;
    }

    /**
     * 取消订单
     *
     * @param $params
     * @return array|mixed|Model
     * @throws DataNotFoundException
     * @throws LogicException
     * @throws ModelNotFoundException
     */
    public function cancel($params)
    {
        $model = $this->getSimpleDetail($params);

        if (1 != $model['status']) {
            throw new LogicException('不可取消订单');
        }

        $model->save(['status' => 7]);
        return $model;
    }

    /**
     * 变更为待填写报告
     *
     * @param $params
     * @return array|mixed|Model
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function report($params)
    {
        $model = $this->getSimpleDetail($params);
        $model->save(['consult_end' => Carbon::now()->timestamp, 'status' => 5]);
        return $model;
    }

    /**
     * 发起退款
     *
     * @param $params
     * @return array|mixed|Model
     * @throws DataNotFoundException
     * @throws LogicException
     * @throws ModelNotFoundException
     */
    public function refund($params)
    {
        $model = $this->getSimpleDetail($params);
        if (!in_array($model['status'], [2, 3]) || !in_array($model['refund_status'], [1, 4])) {
            throw new LogicException('不可退款');
        }

        $result = $model->save(['refund_status' => 2]);
        if ($result) {
            // 发起退款日志
            $insertLogs = [[
                'operator' => $params['operator'],
                'order_consult_id' => $model['id'],
                'log_type' => OrderConsultRefundLogModel::LOG_TYPE_ONE,
                'log_json' => [
                    'relation_data' => [[
                        'data_type' => LogicConstant::LOG_DATA_TYPE_ONE,
                        'data_logic_type' => LogicConstant::LOG_DATA_LOGIC_TYPE_ZERO,
                        'data' => [
                            'key' => '',
                            'value' => '系统审核通过后为您退款'
                        ]
                    ]],
                ],
            ]];
            event('OrderConsultRefundLog', $insertLogs);
        }
        return $model;
    }

    /**
     * 退款审核
     *
     * @param $params
     * @return bool
     */
    public function refundReview($params)
    {
        $model = $this->getSimpleDetail($params);

        Db::connect('communal')->transaction(function () use ($params, &$model) {
            if (4 == $params['refund_status']) {
                // 驳回
                $insertLogs = [[
                    'operator' => $params['admin_name'],
                    'order_consult_id' => $model['id'],
                    'log_type' => OrderConsultRefundLogModel::LOG_TYPE_TWO,
                    'log_json' => [
                        'relation_data' => [[
                            'data_type' => LogicConstant::LOG_DATA_TYPE_ONE,
                            'data_logic_type' => LogicConstant::LOG_DATA_LOGIC_TYPE_TWO,
                            'data' => [
                                'key' => '驳回原因',
                                'value' => $params['refund_remark'] ?? ''
                            ]
                        ]],
                    ],
                ]];
                $model->save($params);
                event('OrderConsultRefundLog', $insertLogs);
            } elseif (3 == $params['refund_status']) {
                // 通过
                switch ($params['refund_way']) {
                    case 1:
                        // 全额
                        $refundAmount = $model['payment_amount'];
                        break;
                    case 2:
                        // 70%
                        $refundAmount = bcmul($model['payment_amount'], '0.7', 2);
                        break;
                    case 3:
                        // 具体金额
                        $refundAmount = $params['refund_amount'];
                        break;
                    default:
                        $refundAmount = 0;
                        break;
                }
                // 创建退款订单 (目前就一个,支持扩)
                $refundModel = OrderConsultRefundModel::where('order_consult_id', $model['id'])->findOrEmpty();
                if ($refundModel->isEmpty()) {
                    $refundModel = invoke(OrderConsultRefundService::class)->create(['order_consult_id' => $model['id'],'payment_amount' => $refundAmount,'deduct_coin' => $model['deduct_coin']]);
                    $number = StringFacade::createStringById($refundModel['id'], 'RC', 16);
                    $numberMd5 = md5($number . Carbon::now());
                    $refundModel->save(['number' => $number, 'out_request_no' => $numberMd5]);
                } else {
                    $numberMd5 = md5($refundModel['number'] . Carbon::now());
                    $refundModel->save(['order_consult_id' => $model['id'],'payment_amount' => $refundAmount,'deduct_coin' => $model['deduct_coin']]);
                }
                $insertLogs = [[
                    'operator' => $params['admin_name'],
                    'order_consult_id' => $model['id'],
                    'order_consult_refund_id' => $model['id'],
                    'log_type' => OrderConsultRefundLogModel::LOG_TYPE_TWO,
                    'log_json' => [
                        'relation_data' => [[
                            'data_type' => LogicConstant::LOG_DATA_TYPE_ONE,
                            'data_logic_type' => LogicConstant::LOG_DATA_LOGIC_TYPE_ZERO,
                            'data' => [
                                'key' => '',
                                'value' => '您的受理已成功'
                            ]
                        ]],
                    ],
                ]];
                $model->save($params);
                event('OrderConsultRefundLog', $insertLogs);

                // 区分支付宝 微信
                if (1 == $model['payment_type']) {
                    // 调用微信退款
                    WechatpayFacade::v3RefundDomesticRefunds(['out_trade_no' => $model['number_md5'], 'out_refund_no' => $numberMd5, 'refund_amount' => $refundAmount * 100, 'payment_amount' => $model['payment_amount'] * 100, 'notify_url' => config('domain.api') . '/callback/wechatConsultRefund']);
                } elseif (2 == $model['payment_type']) {
                    // 支付宝
                    throw new LogicException('暂不支持支付宝退款');
                }
            }
        });
        return $model;
    }

    /**
     * 取消退款
     *
     * @param $params
     * @return array|mixed|Model
     * @throws DataNotFoundException
     * @throws LogicException
     * @throws ModelNotFoundException
     */
    public function unrefund($params)
    {
        $model = $this->getSimpleDetail($params);
        if (2 != $model['refund_status']) {
            throw new LogicException('不可取消退款');
        }

        $model->save(['refund_status' => 1]);
        return $model;
    }

    /**
     * 支付订单
     *
     * @param $order
     * @return string
     * @throws LogicException
     */
    public function payment($order)
    {
        $result = '';
        if (empty($order['number_md5'])) {
            // 订单首次支付
            // 支付订单md5编号
            $numberMd5 = md5($order['number'] . Carbon::now());
            $order->save(['number_md5' => $numberMd5]);
        } else {
            $numberMd5 = $order['number_md5'];
        }
        if ($order['payment_amount'] > 0 && 1 == $order['status']) {
            switch ($order['payment_type']) {
                case 1:
                    // 微信支付
                    $params = [
                        'subject' => $order['name'],
                        'outTradeNo' => $numberMd5,
                        'totalAmount' => (int)bcmul($order['payment_amount'], '100'),
                        'attach' => urlencode(json_encode([
                            // 2 对应 50200_order_consult(单个订单支付)
                            'order_type' => 2,
                        ], JSON_UNESCAPED_UNICODE)),
                        'notify_url' => config('domain.api') . '/callback/wechatpay'
                    ];
                    $result = WechatpayFacade::v3PayTransactionsApp($params);
                    $result = WechatpayFacade::v3AppSign($result['prepay_id']);
                    break;
                case 2:
                    // 支付宝支付
                    $params = [
                        'subject' => $order['name'],
                        'outTradeNo' => $numberMd5,
                        'totalAmount' => $order['payment_amount'],
                        'optionalArgs' => [
                            'passback_params' => urlencode(json_encode([
                                // 2 对应 50200_order_consult(单个订单支付)
                                'order_type' => 2,
                            ], JSON_UNESCAPED_UNICODE)),
                            'query_options' => [],
                        ],
                        'notify_url' => config('domain.api') . '/callback/alipay'
                    ];
                    $result = ALiPayFacade::paymentAppPay($params);
                    break;
                default:
                    break;
            }
        }

        return $result;
    }

    /**
     * 支付订单 debug
     *
     * @param $order
     * @return string
     * @throws LogicException
     */
    public function paymentPage($order)
    {
        $result = '';
        if (empty($order['number_md5'])) {
            // 订单首次支付
            // 支付订单md5编号
            $numberMd5 = md5($order['number'] . Carbon::now());
            $order->save(['number_md5' => $numberMd5]);
        } else {
            $numberMd5 = $order['number_md5'];
        }
        if ($order['payment_amount'] > 0 && 1 == $order['status']) {
            switch ($order['payment_type']) {
                case 1:
                    // 微信支付
                    throw new LogicException('暂不支持微信支付');
                    break;
                case 2:
                    // 支付宝支付
                    $params = [
                        'subject' => $order['name'],
                        'outTradeNo' => $numberMd5,
                        'totalAmount' => $order['payment_amount'],
                        'optionalArgs' => [
                            'passback_params' => urlencode(json_encode([
                                // 2 对应 50200_order_consult
                                'order_type' => 2,
                            ], JSON_UNESCAPED_UNICODE)),
                            'query_options' => [],
                        ],
                        'notify_url' => config('domain.api') . '/callback/alipay'
                    ];
                    $result = ALiPayFacade::paymentPagePay($params);
                    break;
                default:
                    break;
            }
        }

        return $result;
    }

    /**
     * 重新支付
     *
     * @param $params
     * @return array
     * @throws DataNotFoundException
     * @throws LogicException
     * @throws ModelNotFoundException
     */
    public function repay($params)
    {
        $order = $this->getSimpleDetail($params);

        if (0 != $order['group_id']) {
            throw new LogicException('订单组请在消息页面支付');
        }

        Db::connect('communal')->transaction(function () use ($params, $order) {
            // 获取可用元心币
            $availableCoin = invoke(StatisticsService::class)->getCoinAvailableCountByUserId($params['user_id']);
            $deductCoin = 1 == $params['is_coin'] ? $availableCoin : '0'; // 抵扣用元心币数量
            list($paymentAmount, $deductAmount, $deductCoin) = StringFacade::orderPayment($order['total_amount'], $deductCoin);
            if ($deductCoin != $order['deduct_coin']) {
                // 先把原订单对应元心币解锁再冻结
                invoke(StatisticsService::class)->unfreezeCoin($order['user_id'], $order['deduct_coin']);
                invoke(StatisticsService::class)->freezeCoin($order['user_id'], $deductCoin);
            }
            $order->save(['payment_amount' => $paymentAmount, 'deduct_amount' => $deductAmount, 'deduct_coin' => $deductCoin, 'payment_type' => $params['payment_type']]);
        });

        $payment = $this->payment($order);
        // $payment = $this->paymentPage($order); // debug
        return [
            'order' => $order,
            'payment' => $payment,
        ];
    }

    /**
     * 支付宝回调处理
     *
     * @param $params
     */
    public function aLiPayCallback($params)
    {
        Log::debug('Callback_ALiPay_order_consult_params: ' . var_export($params, true));
        // 签名验证后
        $check = ALiPayFacade::paymentCommonVerifyNotify($params);
        Log::debug('Callback_ALiPay_order_consult_out_trade_no: ' . $params['out_trade_no'] . ',验签结果: ' . $check);
        if (!$check) {
            return ;
        }

        $update = [];
        $tradeStatus = $params['trade_status'] ?? '';
        if (isset($params['trade_status']) && 'TRADE_SUCCESS' == $params['trade_status']) {
            // 支付成功
            // Log::debug('Callback_ALiPay_order_multi_debug');
            // 冻结元心币消耗
            // 增加元心币消费明细
            // 去事件里面搞吧...
            event('OrderConsultPaySuccess', ['out_trade_no' => $params['out_trade_no'], 'trade_status' => $tradeStatus]); // 可队列
        } else {
            // 更新订单信息
            $update['trade_status'] = $tradeStatus;
            OrderConsultModel::where('number_md5', $params['out_trade_no'])->update($update);
        }
    }

    /**
     * 微信回调处理
     *
     * @param $params
     */
    public function wechatPayCallback($params)
    {
        Log::debug('Callback_wechatPay_order_consult_params: ' . var_export($params, true));

        $update = [];
        $tradeStatus = $params['trade_state'] ?? '';
        if (isset($params['trade_state']) && 'SUCCESS' == $params['trade_state']) {
            // 支付成功
            // Log::debug('Callback_ALiPay_order_multi_debug');
            // 冻结元心币消耗
            // 增加元心币消费明细
            // 去事件里面搞吧...
            event('OrderConsultPaySuccess', ['out_trade_no' => $params['out_trade_no'], 'trade_status' => $tradeStatus]); // 可队列
        } else {
            // 更新订单信息
            $update['trade_status'] = $tradeStatus;
            OrderConsultModel::where('number_md5', $params['out_trade_no'])->update($update);
        }
    }

    /**
     * 支付成功
     *
     * @param $outTradeNo
     * @param string $tradeStatus
     */
    public function paySuccess($outTradeNo, $tradeStatus = '')
    {
        $model = OrderConsultModel::where('number_md5', $outTradeNo)->findOrEmpty();
        if (!$model->isEmpty() && 1 == $model['status']) {
            Db::connect('communal')->transaction(function () use ($model, $outTradeNo, $tradeStatus) {
                $model->save(['status' => 2, 'trade_status' => $tradeStatus]);
                // 冻结元心币消耗
                // 增加元心币消费明细
                invoke(StatisticsService::class)->consumeFreezeCoin($model['user_id'], $model['deduct_coin'], 2);
                // 增加累积消费 并 试图返点
                invoke(StatisticsService::class)->accrueCost($model['user_id'], $model['payment_amount']);
            });
        }
    }

    /**
     *  write a report
     *
     * @param $params
     * @return array|mixed|Model
     * @throws DataNotFoundException
     * @throws LogicException
     * @throws ModelNotFoundException
     */
    public function writeReport($params)
    {
        $order = $this->getSimpleDetail($params);

        if (5 != $order['status']) {
            throw new LogicException('暂不可填写报告');
        }
        // 获取分润率设置
        $ratioConfig = invoke(InfoService::class)->getSimpleDetail(['type' => 10])->toArray();
        if (empty($ratioConfig) || !isset($ratioConfig['content']) || !isset($ratioConfig['content']['common_multi'])
            || !isset($ratioConfig['content']['common_consult']) || !isset($ratioConfig['content']['company_consult'])
        ) {
            throw new LogicException('分润率未设置,请联系客服');
        }

        Db::connect('communal')->transaction(function () use ($params, $ratioConfig, &$order) {
            if (1 == $order['type']) {
                // 量表解读
                if (1 != $order['is_coupon']) {
                    // 个人订单
                    // common_multi
                    $ratio = $ratioConfig['content']['common_multi'];
                    $ratioType = 2;
                } else {
                    // 使用企业券
                    // 无处理
                    $ratioType = 1;
                    $ratio = 0;
                }
            } else {
                // 心理咨询
                if (1 == $order['is_coupon']) {
                    // 使用企业券
                    $ratio = $ratioConfig['content']['company_consult'];
                    $ratioType = 1;
                } else {
                    // 个人订单
                    $ratio = $ratioConfig['content']['common_consult'];
                    $ratioType = 2;
                }
            }

            if ($ratio > 0) {
                // 存在分润率
                $totalAmount = $order['total_amount'];
                // 分润金额
                $sharingAmount = bcmul(bcdiv((string)$ratio, '100', 2), $totalAmount, 2);
                invoke(ExpertAmountService::class)->back([
                    'expert_id' => $order['expert_id'],
                    'amount_count' => $sharingAmount,
                    'type' => $ratioType,
                ]);
            }
            // 填写报告
            $order->save($params);
        });

        return $order;
    }
}
